<?php

namespace app\controllers\api;

use app\models\custom\Identity;
use app\models\User;
use Yii;
use yii\base\Exception;
use yii\base\UserException;

class UserController extends BaseController {
    // 用户登录处理
    public function actionLogin() {
        Yii::$app->user->logout();

        $login_name = Yii::$app->request->post('login_name');
        $password = Yii::$app->request->post('password');
        $user = User::findOne(['username' => $login_name]);
        // 用户不存在直接返回
        if (!$user) {
            return $this->renderError('用户名不存在');
        }

        // 验证密码
        if (!$this->validatePassword($user, $password)) {
            return $this->renderError('密码错误');
        }

        $identity = new Identity($user);
        if (!Yii::$app->user->login($identity, 300)) {
            throw new Exception('登陆失败');
        }
        $this->log('用户 - 登录', '');

        return $this->renderSuccess([
            'user'=>$user
        ]);
    }

    // 用户 修改密码
    public function actionPassword() {
        $user = $this->check();
        $old = Yii::$app->request->post('old');
        $new = Yii::$app->request->post('new');
        // 验证密码
        if (!$this->validatePassword($user, $old)) {
            return $this->renderError('旧密码错误');
        }
        if (empty($new)) {
            return $this->renderError('新密码不能为空');
        }

        $user->password = Yii::$app->security->generatePasswordHash($new);
        $user->save(true, ['password']);
        $this->log('用户 - 修改密码', '');

        return $this->renderSuccess([
            'user'=>$user
        ]);
    }

    // 验证密码是否正确
    protected function validatePassword(User $user, $password) {
        return !empty($user->password) && !empty($password) && Yii::$app->security->validatePassword($password, $user->password);
    }

    // 升级原料水晶
    public function actionLevelUp() {
        $user = $this->check();
        $this->checkModify();
        if($user->material_level >= $this->getConfig('upgrade-max-level', 0)) {
            throw new UserException('当前已是最高等级');
        }

        $this->transaction(function() use($user) {
            $money = $this->getConfig('upgrade-base-cost', 0) +
                ($user->material_level - $this->getConfig('upgrade-min-level', 0)) * $this->getConfig('upgrade-increase-cost', 0);
            $user->material_level ++;
            $this->log('用户 - 原料水晶升级', '', -$money);
            $this->logForUser(User::findOne(['role'=>'4']), '原料水晶升级-收入', '', $money);
        });

        return $this->renderSuccess([]);
    }

    // 其他用户列表
    public function actionOtherList() {
        $user = $this->check();
        $models = User::find()->andWhere(['<>', 'id', $user->id])->all();

        return $this->renderSuccess([
            'list' => $models,
        ]);
    }
}
